package com.ld.common;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ld.emun.ErrorCodeEnum;
import com.ld.exception.BusinessException;
import lombok.Data;

import java.util.HashMap;
import java.util.List;

@Data
public class ResultInfoFactory<T> {

    private long code;

    private String message;

    private T data;

    private boolean success = true;
    @JsonIgnore
    private static final Object DEFAULT_DATA = new HashMap<>(0);

    public static ResultInfoFactory success() {
        return create(CommonConstant.REQUEST_SUCCESS_CODE, CommonConstant.REQUEST_SUCCESS_MESSAGE, true);
    }

    public static <T> ResultInfoFactory<T> success(T data) {
        return create(CommonConstant.REQUEST_SUCCESS_CODE, CommonConstant.REQUEST_SUCCESS_MESSAGE, data, true);
    }

    public static ResultInfoFactory failed() {
        return create(CommonConstant.REQUEST_FAILED_CODE, CommonConstant.REQUEST_FAILED_MESSAGE, false);
    }

    public static ResultInfoFactory failed(long code, String message) {
        return create(code, message, false);
    }

    public static ResultInfoFactory failed(String message) {
        return create(CommonConstant.REQUEST_FAILED_CODE, message, false);
    }

    public static ResultInfoFactory failed(ErrorCodeEnum errorCodeEnum) {
        return create(errorCodeEnum.getCode(), errorCodeEnum.getMessage(), false);
    }

    public static ResultInfoFactory failed(ErrorCodeEnum errorCodeEnum, List data) {
        return create(errorCodeEnum.getCode(), errorCodeEnum.getMessage(), data, true);
    }

    public static ResultInfoFactory failed(BusinessException e) {
        return create(e.getCode(), e.getMessage(), false);
    }



    private static ResultInfoFactory create(long code, String message, boolean success) {
        ResultInfoFactory result = new ResultInfoFactory<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(DEFAULT_DATA);
        result.setSuccess(success);
        return result;
    }

    private static <T> ResultInfoFactory<T> create(long code, String message, T data, boolean success) {
        ResultInfoFactory<T> result = new ResultInfoFactory<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        result.setSuccess(success);
        return result;
    }

    public String toJsonString(Object object){
        return JSON.toJSONString(object);
    }
}
